<?php
namespace App\Service\Admin;

class EmojiService extends BaseService
{
    //表情包

    /**
     * 列表
     * @param array $pages【start，limit】
     */
    public function getIndex($pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbEmoji)
            ->where('del', 0);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            if (substr($v['link'], 0, 4) == 'http') {
                $link = $v['link'];
            } else {
                $link = file_exists($v['link']) ? env('DOMAIN').'/'.$v['link'] : '';
            }
            $arys[] = [
                'id' => $v['id'],
                'title' => $v['title'],
                'link' => $link,
                'uptime' => $v['uptime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    //添加
    public function add($pas)
    {
        $res = (array) $this->dbConn($this->dbEmoji)
            ->where('del', 0)
            ->where('title', $pas['title'])
            ->first();
        if (!empty($res)) {
            return $this->toback(-2, '已存在同名记录');
        }
        $pas['uptime'] = $pas['addtime'] = toDate();
        $lastid = $this->dbConn($this->dbEmoji)->insertGetId($pas);
        if (!$lastid) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    //修改
    public function modify($id, $pas)
    {
        $res = $this->dbConn($this->dbEmoji)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '没有记录');
        }
        $pas['uptime'] = toDate();
        $up = $this->dbConn($this->dbEmoji)->where('id', $id)->update($pas);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    //删除
    public function del($id)
    {
        $res = $this->dbConn($this->dbEmoji)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '没有记录');
        }
        $up = $this->dbConn($this->dbEmoji)->where('id', $id)
            ->update(['del' => 1, 'deltime' => toDate()]);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }
}